package mas.agents;

import java.io.IOException;
import java.sql.ResultSet;


import done.DBConnection;
import mas.patternRec.Patterns;
import jade.core.Agent;
import jade.core.behaviours.OneShotBehaviour;
import jade.lang.acl.ACLMessage;

public class PatRecAgent extends Agent {
	
	@Override
	protected void setup() {
		System.out.println("Pattern Agent Online.");
		
		addBehaviour(new OneShotBehaviour() {
			
			@Override
			public void action() {
				ACLMessage msg = myAgent.blockingReceive();				
				if (msg.getContent().equals(Ontology.DB_READY_MSG)) {
					System.out.println(myAgent.getLocalName() + " recieved DB_READY. Starting pattern detection...");
					detectPatterns();
					
					ACLMessage msgToVisualizator = Ontology.createInformMessage(AgentNicknames.VISUALIZATION_AGENT, 
							Ontology.PATTERNS_READY_MSG);	
					send(msgToVisualizator);
				}
				
			}

			private void detectPatterns() {
				if (DBConnection.conn == null) 
					DBConnection.initConnection();
				
				DBConnection.readyInserts();
				ResultSet resSet = DBConnection.selectData("SELECT id, timestamp FROM action_ids");
				try {
					Patterns.detect(resSet, 2);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				DBConnection.closeInserts();				
			}
		});
	}
	
	public static void main(String[] args) {		
		
//		
//		Statement stmt;
//		try {
//			stmt = DBConnection.conn.createStatement();
//			stmt.execute("insert into action_ids (id, timestamp, name) VALUES (354, '2009-07-09T21:54:21Z', 'doX')");
//		} catch (SQLException e1) {
//			// TODO Auto-generated catch block
//			e1.printStackTrace();
//		}
//		
		DBConnection.readyInserts();
		ResultSet resSet = DBConnection.selectData("SELECT id, timestamp FROM action_ids");
		try {
			Patterns.detect(resSet, 2);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		DBConnection.closeInserts();
	}
	
	@Override
	protected void takeDown() {
		System.out.println("Pattern Recognition Agent OFFLINE.");
	}

}
